package com.sgcc.operate.service.impl;

import com.sgcc.common.security.service.TokenService;
import com.sgcc.operate.domain.OMonsysMenu;
import com.sgcc.operate.domain.OMonsysStaff;
import com.sgcc.operate.domain.vo.MonsysMenuDataDto;
import com.sgcc.operate.mapper.OMonsysMenuMapper;
import com.sgcc.operate.mapper.OMonsysStaffMapper;
import com.sgcc.operate.service.IOMonsysMenuService;
import com.sgcc.operate.util.DateFormatUtil;
import com.sgcc.operate.util.ListUtil;
import com.sgcc.system.api.RemoteDictDataService;
import com.sgcc.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能菜单明细Service业务层处理
 * 
 * @author sgcc
 * @date 2021-04-10
 */
@Service
public class OMonsysMenuServiceImpl implements IOMonsysMenuService 
{
    @Autowired
    private OMonsysMenuMapper oMonsysMenuMapper;
    @Autowired
    private RemoteDictDataService remoteDictDataService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private OMonsysStaffMapper oMonsysStaffMapper;

    /**
     * 查询功能菜单明细
     * 
     * @param id 功能菜单明细ID
     * @return 功能菜单明细
     */
    @Override
    public OMonsysMenu selectOMonsysMenuById(String id)
    {
        return oMonsysMenuMapper.selectOMonsysMenuById(id);
    }

    /**
     * 查询功能菜单明细列表
     * 
     * @param oMonsysMenu 功能菜单明细
     * @return 功能菜单明细
     */
    @Override
    public List<OMonsysMenu> selectOMonsysMenuList(OMonsysMenu oMonsysMenu)
    {
        return oMonsysMenuMapper.selectOMonsysMenuList(oMonsysMenu);
    }

    /**
     * 新增功能菜单明细
     * 
     * @param oMonsysMenu 功能菜单明细
     * @return 结果
     */
    @Override
    public int insertOMonsysMenu(OMonsysMenu oMonsysMenu)
    {
        OMonsysMenu parent = new OMonsysMenu();
        // 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
        if (StringUtils.isBlank(oMonsysMenu.getParentId())
                || "00000".equals(oMonsysMenu.getParentId()) || "0".equals(oMonsysMenu.getParentId()) ){
            oMonsysMenu.setParentId("0");
            parent.setParentId("0");
            parent.setParentIds("");
        }else{
            parent = selectOMonsysMenuById(oMonsysMenu.getParentId());
            oMonsysMenu.setMonSysCode(parent.getMonSysCode());
        }
        // 获取修改前的parentIds，用于更新子节点的parentIds
//        String oldParentIds = entity.getParentIds();
        // 设置新的父节点串
        String newParentIds = parent.getParentIds()+parent.getId()+",";
        oMonsysMenu.setParentIds(newParentIds);
        // 设置菜单等级
        String[] newParentIdsSplit = newParentIds.split(",");
        String menuLevel =  (newParentIdsSplit.length - 1) < 0 ? 0 + "" : (newParentIdsSplit.length - 1) + "";
        oMonsysMenu.setMenuLevel(menuLevel);
        //不添加等级大于3数据
        if (Integer.valueOf(menuLevel) > 4) {
            return 0;
        }

        //设置新父级是否有子集
        if (parent != null && parent.getId() != null && !"0".equals(parent.getId()) && !"1".equals(parent.getId())){
            parent.setIsPar("1");
            oMonsysMenuMapper.updateOMonsysMenu(parent);
        }

        //维护人设置
        LoginUser user = tokenService.getLoginUser();
        String loginName = user.getSysUser().getNickName();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(loginName)){
            oMonsysMenu.setOperStaff(loginName);
        }else {
            oMonsysMenu.setOperStaff("admin");
        }
        //维护时间设置
        Date nowDate = new Date();
//		String nowDateStr = DateFormatUtil.formatDate("yyyy-MM-dd HH:mm", nowDate);
        oMonsysMenu.setOperTime(nowDate);
        oMonsysMenu.setCreateBy(user.getUserid());
        oMonsysMenu.setUpdateBy(user.getUserid());
        oMonsysMenu.setDelFlag("0");
        String id= UUID.randomUUID().toString().replaceAll("-", "");
        oMonsysMenu.setId(id);
        oMonsysMenu.setIsPar("0");
        oMonsysMenu.setCreateTime(new Date());
        oMonsysMenu.setUpdateTime(new Date());
        return oMonsysMenuMapper.insertOMonsysMenu(oMonsysMenu);
    }

    /**
     * 修改功能菜单明细
     * 
     * @param oMonsysMenu 功能菜单明细
     * @return 结果
     */
    @Override
    public int updateOMonsysMenu(OMonsysMenu oMonsysMenu)
    {
        OMonsysMenu oldO = selectOMonsysMenuById(oMonsysMenu.getId());
        OMonsysMenu parent = new OMonsysMenu();
        // 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
        if (StringUtils.isBlank(oMonsysMenu.getParentId())
                || "00000".equals(oMonsysMenu.getParentId()) || "0".equals(oMonsysMenu.getParentId()) ){
            oMonsysMenu.setParentId("0");
            parent.setParentId("0");
            parent.setParentIds("");
        }else{
            parent = selectOMonsysMenuById(oMonsysMenu.getParentId());
            oMonsysMenu.setMonSysCode(parent.getMonSysCode());
        }
        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = oldO.getParentIds();
        // 设置新的父节点串
        String newParentIds = parent.getParentIds()+parent.getId()+",";
        oMonsysMenu.setParentIds(newParentIds);
        // 设置菜单等级
        String[] newParentIdsSplit = newParentIds.split(",");
        String menuLevel =  (newParentIdsSplit.length - 1) < 0 ? 0 + "" : (newParentIdsSplit.length - 1) + "";
        oMonsysMenu.setMenuLevel(menuLevel);
        //不添加等级大于3数据
        if (Integer.valueOf(menuLevel) > 4) {
            return 0;
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(oMonsysMenu.getId())) {
            String newPid = parent.getId();
            //设置老父级是否有子集
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(oldParentIds)) {
                String[] oldParentIdsSplit = oldParentIds.split(",");
                String oldPid = oldParentIdsSplit[oldParentIdsSplit.length - 1];
                OMonsysMenu oldParent = selectOMonsysMenuById(oldPid);
                if (null != oldParent && null != oldParent.getId() && !oldParent.getId().equals(newPid)) {
                    List<OMonsysMenu> oldChildren = oMonsysMenuMapper.getChildren(oldParent.getId());
                    int oldChildrenSize = (ListUtil.isNotEmpty(oldChildren) && null != oldChildren.get(0)) ? oldChildren.size() : 0;
                    if ((oldChildrenSize - 1) > 0) {
                        oldParent.setIsPar("1");
                    }else {
                        oldParent.setIsPar("0");
                    }
                    oMonsysMenuMapper.updateOMonsysMenu(oldParent);
                }
            }
        }
        //设置新父级是否有子集
        if (parent != null && parent.getId() != null && !"0".equals(parent.getId()) && !"1".equals(parent.getId())){
            parent.setIsPar("1");
            oMonsysMenuMapper.updateOMonsysMenu(parent);
        }
        // 更新子节点 parentIds
        OMonsysMenu o = new OMonsysMenu();
        o.setParentIds("%,"+oMonsysMenu.getId()+",%");
        List<OMonsysMenu> list = oMonsysMenuMapper.findByParentIdsLike(o);
        //设置是否有子集
        if (ListUtil.isNotEmpty(list) && null != list.get(0)) {
            oMonsysMenu.setIsPar("1");
        }else {
            oMonsysMenu.setIsPar("0");
        }
        for (OMonsysMenu e : list){
            if (e.getParentIds() != null && oldParentIds != null){
                String newChildPids = e.getParentIds().replace(oldParentIds, oMonsysMenu.getParentIds());
                e.setParentIds(newChildPids);
//                preUpdateChild(entity, e);
                String[] newChildPidsSplit = newChildPids.split(",");
                String childMenuLevel =  (newChildPidsSplit.length - 1) < 0 ? 0 + "" : (newChildPidsSplit.length - 1) + "";
                e.setMenuLevel(childMenuLevel);
                oMonsysMenuMapper.updateParentIds(e);
            }
        }
        //维护人设置
        LoginUser user = tokenService.getLoginUser();
        String loginName = user.getSysUser().getNickName();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(loginName)){
            oMonsysMenu.setOperStaff(loginName);
        }else {
            oMonsysMenu.setOperStaff("admin");
        }
        //维护时间设置
        Date nowDate = new Date();
//		String nowDateStr = DateFormatUtil.formatDate("yyyy-MM-dd HH:mm", nowDate);
        oMonsysMenu.setOperTime(nowDate);
        oMonsysMenu.setUpdateBy(user.getUserid());
        return oMonsysMenuMapper.updateOMonsysMenu(oMonsysMenu);
    }

    /**
     * 批量删除功能菜单明细
     * 
     * @param ids 需要删除的功能菜单明细ID
     * @return 结果
     */
    @Override
    public int deleteOMonsysMenuByIds(String[] ids)
    {
        return oMonsysMenuMapper.deleteOMonsysMenuByIds(ids);
    }

    /**
     * 删除功能菜单明细信息
     * 
     * @param id 功能菜单明细ID
     * @return 结果
     */
    @Override
    public int deleteOMonsysMenuById(String id)
    {
        return oMonsysMenuMapper.deleteOMonsysMenuById(id);
    }

    @Override
    public List<MonsysMenuDataDto> monsysMenuDataList(MonsysMenuDataDto menu) {
        List<MonsysMenuDataDto> result = new ArrayList<>();
        Map<String, Object> condition = new HashMap<>(16);
        Map<Integer, String> cache = new HashMap<>(16);
        int nowLevel = 0;
        condition.put("entity", menu);
        condition.put("parentId", "1");
        String monSysCode = menu.getMonSysCode();
        String treeId = menu.getId();
        String menuLevel = menu.getMenuLevel();
        ArrayList<String> menuLevels = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(menuLevel)) {
            menu.setName(null);
            condition.put("treeId", treeId);
            switch(menuLevel){
                case "0":
                    //列表展示所有级联数据
                    condition.put("treeId", null);
                    menuLevels = ListUtil.newArrayList("0", "1", "2", "3", "4");
                    //列表展示当前级别数据
//					menuLevels = ListUtil.newArrayList("1", "2", "3", "4");
                    break;
                case "1":
                    //列表展示所有级联数据
                    condition.put("treeId", null);
                    menuLevels = ListUtil.newArrayList( "1", "2", "3", "4");
                    //列表展示当前级别数据
//					menuLevels = ListUtil.newArrayList("2", "3", "4");
                    break;
                case "2":
                    menuLevels = ListUtil.newArrayList("2", "3", "4");
                    break;
                case "3":
                    menuLevels = ListUtil.newArrayList("3", "4");
                    break;
                case "4":
                    menuLevels = ListUtil.newArrayList("3", "4");
                    break;
                default:
                    menuLevels = ListUtil.newArrayList("-1");
                    break;
            }
        }
        condition.put("menuLevels", menuLevels);
        List<OMonsysMenu> parentsSours = getChildrenEx(condition);
        List<OMonsysMenu> parentsTarget = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isEmpty(monSysCode)) {
//		if (!pageFlag) {
            parentsTarget = parentsSours;
        }else {
            for (OMonsysMenu parent : parentsSours) {
                String pMonSysCode = parent.getMonSysCode();
                if (monSysCode.equals(pMonSysCode)) {
                    parentsTarget.add(parent);
                }
            }
        }
        this.addMonsysMenuData(parentsTarget, nowLevel, condition, cache, result, menu);
        Collections.sort(result);
        return result;
    }

    //递归查询相应数据
    private void addMonsysMenuData(List<OMonsysMenu> parents, int nowLevel, Map<String, Object> condition, Map<Integer, String> cache, List<MonsysMenuDataDto> result, MonsysMenuDataDto entity) {
        if (ListUtil.isNotEmpty(parents) && null != parents.get(0)) {
            nowLevel ++;
            for (OMonsysMenu parent : parents) {
                String pid = parent.getId();
                String monSysCode = parent.getMonSysCode();
                String monSysName = remoteDictDataService.getLabel("SysCode", monSysCode);
                if(monSysName==null){
                    monSysName="未知系统";
                }
                condition.put("parentId", pid);
                condition.put("isPar", "0");
                entity.setMonSysCode( monSysCode);
                cache.put(nowLevel - 1, parent.getName());
                List<OMonsysMenu> oneChildren = oMonsysMenuMapper.findMonsysMenuData(condition);
                if (ListUtil.isNotEmpty(oneChildren) && null != oneChildren.get(0)) {
                    for (OMonsysMenu oneChild : oneChildren) {
                        MonsysMenuDataDto item = new MonsysMenuDataDto();
                        String id = oneChild.getId();
                        String itemName = oneChild.getName();
                        cache.put(nowLevel,itemName);
                        item.setId(id);
                        item.setMonSysCodeName(monSysName);
                        item.setMenuExplain(oneChild.getMenuExplain());
                        Date releaseTime = oneChild.getReleaseTime();
                        if (null != releaseTime) {
                            item.setReleaseTime(DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, releaseTime));
                        }
                        Date operTime = oneChild.getOperTime();
                        if (null != operTime) {
                            item.setOperTime(DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, operTime));
                        }
                        item.setOperStaff(oneChild.getOperStaff());
                        item.setAccePath(oneChild.getAccePath());
                        String itemLevel = oneChild.getMenuLevel();
                        switch(itemLevel){
                            case "2":
                                item.setOneName(cache.get(1));
                                item.setTwoName("");
                                item.setThreeName("");
                                break;
                            case "3":
                                item.setOneName(cache.get(1));
                                item.setTwoName(cache.get(2));
                                item.setThreeName("");
                                break;
                            case "4":
                                item.setOneName(cache.get(1));
                                item.setTwoName(cache.get(2));
                                item.setThreeName(cache.get(3));
                                break;
                            default:
                                break;
                        }
                        result.add(item);
                    }
                }
                condition.put("isPar", "1");
                List<OMonsysMenu> oneParents = oMonsysMenuMapper.findMonsysMenuData(condition);
                addMonsysMenuData(oneParents, nowLevel, condition, cache, result, entity);
            }
        }
    }


    @Override
    public List<OMonsysMenu> getChildrenEx(Map<String, Object> condition) {
        String parentId = (String) condition.get("parentId");
        if (org.apache.commons.lang3.StringUtils.isEmpty(parentId)) {
            parentId = "1";
            condition.put("parentId", parentId);
        }
        List<OMonsysMenu> result = new ArrayList<>();
        LoginUser user = tokenService.getLoginUser();


        String userId = "1";
        if (null != user && null != user.getUserid()) {
            userId = user.getUserid();
        }
        OMonsysStaff staffCondition = new OMonsysStaff();
        staffCondition.setStaffNo(userId);
        List<OMonsysStaff> authList = oMonsysStaffMapper.selectOMonsysStaffList(staffCondition);
        condition.put("authList", authList);
        if (ListUtil.isNotEmpty(authList) && null != authList.get(0)) {
            result = oMonsysMenuMapper.getChildrenEx(condition);
            return result;
        }else {
            return result;
        }
    }


    @Override
    public List<OMonsysMenu> findListEx(OMonsysMenu menu) {
        List<OMonsysMenu> result = new ArrayList<>();
        LoginUser user = tokenService.getLoginUser();
        String userId = "1";
        if (null != user && null != user.getUserid()) {
            userId = user.getUserid();
        }
        OMonsysStaff staffCondition = new OMonsysStaff();
        staffCondition.setStaffNo(userId);
        List<OMonsysStaff> authList = oMonsysStaffMapper.selectOMonsysStaffList(staffCondition);
        if (ListUtil.isNotEmpty(authList) && null != authList.get(0)) {
            result = oMonsysMenuMapper.findAuthList(authList);
            return result;
        }else {
            return result;
        }
    }
}
